const {mysql} = require('../../qcloud')
//添加购物车（goods/goods.vue/addCart 方法）
async function addCart(ctx){
	const {openId, goodsId,number} = ctx.request.body
	const haveGoods = await mysql('nideshop_cart').where({
	    'user_id': openId,
	    'goods_id': goodsId
	}).select()
	//如果在购物车表中找不到数据，连接商品表，取出价格、名字、图片字段放在goods数组中
  	if (haveGoods.length === 0) {
    	const goods = await mysql('nideshop_goods').where({
      		'id': goodsId
    	}).select()
    	const { retail_price, name, list_pic_url } = goods[0]
	    // 向购物车表中插入以下字段
	    await mysql('nideshop_cart').insert({
	      'user_id': openId,
	      'goods_id': goodsId,
	      number,
	      'goods_name': name,
	      retail_price,
	      list_pic_url
	    })
  	} else { //如果购物车表中已存在该数据
  		//在购物车表中找到number字段
	    const oldNumber = await mysql('nideshop_cart').where({
	      	'user_id': openId,
	      	'goods_id': goodsId
	    }).column('number').select()
	    // 更新number数据
	    await mysql('nideshop_cart').where({
	      	'user_id': openId,
	      	'goods_id': goodsId
	    }).update({
	      	'number': oldNumber[0].number + number
	    })
	}
  ctx.state = {
    data: 'success'
  }
}

// 获取购物车列表（ cart/cart.vur/getListData 方法）
async function cartList(ctx) {
  const { openId } = ctx.query
  const cartList = await mysql('nideshop_cart').where({
    'user_id': openId
  }).select()

  const oldData = await mysql('nideshop_cart').where({
    'user_id': openId
  }).select()
    let allnumber = 0
    if (oldData.length > 0) {
      for (let i = 0; i < oldData.length; i++) {
        allnumber ++ //总数量
      }
    }
  ctx.state.data= {
    cartList,allnumber
  }
}

//购物车删除 （ cart/cart.vue/delCarts 方法）
async function delCart(ctx){
	const {goodsId , openId} = ctx.request.body
	const delData = await mysql('nideshop_cart').andWhere({
	    'user_id': openId
	}).whereIn('goods_id', goodsId.split(',')).del()
	ctx.state = {
		data:true
	}
} 

// 购物车中商品数量的变化（  cart/cart.vue/add 方法）
async function cartNumber(ctx){ 
	const { goodsId , openId , flag} = ctx.request.body
	const oldData = await mysql('nideshop_cart').where({
		'user_id': openId,
		'goods_id': goodsId
	}).select()
	let newNumber = 1
	if(oldData){
	// 	 添加数量
		if(flag){
			newNumber += oldData[0].number
		 	await mysql('nideshop_cart').where({
			 	'user_id':openId,
			 	'goods_id':goodsId
		 	}).update({
		 		number:newNumber
		 	})
		}else{
	 		// 减少数量
			newNumber = oldData[0].number - newNumber
		 	await mysql('nideshop_cart').where({
			 	'user_id':openId,
			 	'goods_id':goodsId
		 	}).update({
		 		number:newNumber
		 	})
		}	 
	}
	ctx.state.data = {
		newNumber
	}
}

module.exports = {
	addCart,
	cartList,
	delCart,
	cartNumber
}